package com.bua.net;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

/**
 * 静态工具类
 * 
 * @author leizhang
 * 
 */
public class Tool {

	public static final String SH_PRE_NAME = "UboxShare";

	public static final String MAC_SHARE = "mac";

	/**
	 * 正整数正则表达式
	 */
	public static final String positive_integer_regexp = "^[0-9]*[1-9][0-9]*$";

	/**
	 * 是否是模拟器
	 * 
	 * @return
	 */
	public static final boolean isSimulator() {
		String model = Build.MODEL, product = Build.PRODUCT;
		return (model != null && model.toLowerCase().equals("sdk")
				&& product != null && product.toLowerCase().equals("sdk"));
	}

	/**
	 * 从输入流读取数据
	 * 
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	public static byte[] readInputStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		outSteam.close();
		inStream.close();
		return outSteam.toByteArray();
	}

	/**
	 * UTF-8 Encode
	 * 
	 * @param value
	 * @return
	 */
	public static String UTFCode(String value) {
		String resultValue = null;

		try {
			resultValue = URLEncoder.encode(value, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return resultValue;
	}

	/**
	 * Activity跳转方法
	 * 
	 * @param srcClass
	 *            当前Activity
	 * @param descClass
	 *            目标Activity
	 */
	/**
	 * @param srcClass
	 * @param descClass
	 */
	// public static void forwardTarget(Activity srcClass, Class<?> descClass) {
	// forwardTarget(srcClass, descClass, UIConfig.RESQUEST_CODE_NULL);
	// }

	/**
	 * Activity跳转方法
	 * 
	 * @param srcClass
	 *            当前Activity
	 * @param descClass
	 *            目标Activity
	 */
	/**
	 * @param srcClass
	 * @param descClass
	 * @param bundle
	 */
	// public static void forwardTarget(Activity srcClass, Class<?> descClass,
	// Bundle bundle) {
	// forwardTarget(srcClass, descClass, UIConfig.RESQUEST_CODE_NULL, bundle);
	// }

	/**
	 * Activity跳转方法
	 * 
	 * @param srcClass
	 *            当前Activity
	 * @param descClass
	 *            目标Activity
	 * @param requestCode
	 *            返回标识(标识是哪个Activity返回的)
	 */
	/**
	 * @param srcClass
	 * @param descClass
	 * @param requestCode
	 */
	// public static void forwardTarget(Activity srcClass, Class<?> descClass,
	// int requestCode) {
	// Intent intent = new Intent();
	// intent.setClass(srcClass.getApplicationContext(), descClass);
	// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	// srcClass.startActivityForResult(intent, requestCode);
	// }

	/**
	 * 带数据的跳转
	 * 
	 * @param srcClass
	 *            当前
	 * @param descClass
	 *            目标
	 * @param requestCode
	 *            返回Activity标识
	 * @param bundle
	 *            传递的数据
	 */
	/**
	 * @param srcClass
	 * @param descClass
	 * @param requestCode
	 * @param bundle
	 */
	// public static void forwardTarget(Activity srcClass, Class<?> descClass,
	// int requestCode, Bundle bundle) {
	// Intent intent = new Intent();
	// intent.setClass(srcClass.getApplicationContext(), descClass);
	// intent.putExtras(bundle);
	// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	// srcClass.startActivityForResult(intent, requestCode);
	// }
	//
	/**
	 * 
	 */
	private static Toast toast;

	/**
	 * @param context
	 * @param msg
	 */
	public static void showToast(Context context, String msg) {

		toast = Toast.makeText(context.getApplicationContext(), msg, 2000);
		toast.show();
	}

	/**
	 * 获取MD5后的用户密码
	 * 
	 * @param userPassword
	 * @return
	 */
	/**
	 * @param userPassword
	 * @return
	 */
	public static String getUserPasswordMD5(String userPassword) {
		String user_Password = "";
		byte[] srcBytes = { 0 };
		// 对用户密码进行md5
		if (userPassword != null && !userPassword.equalsIgnoreCase("")) {
			try {
				srcBytes = userPassword.getBytes("UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			// UserInfoBean.USER_PASSWORD_MD5 = toMd5(srcBytes);
			user_Password = toMd5(srcBytes);
			// Tool.Log("stone","user MD5 pswd=["+user_Password+"]");
		}
		return user_Password;
	}

	public static final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5',
			'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	public static String toHexString(byte[] bytes) {
		StringBuilder sb = new StringBuilder(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			sb.append(HEX_DIGITS[(bytes[i] & 0xf0) >>> 4]);
			sb.append(HEX_DIGITS[bytes[i] & 0x0f]);
		}
		return sb.toString();
	}

	/**
	 * MD5 加密
	 * 
	 * @param bytes
	 * @return
	 */
	public static String toMd5(byte[] bytes) {
		String result_md5 = "";
		try {
			MessageDigest algorithm = MessageDigest.getInstance("MD5");
			algorithm.reset();
			algorithm.update(bytes);
			result_md5 = toHexString(algorithm.digest());
			// Tool.Log("stone", " @@@@@@@@@@ MD5=["+result_md5+"]");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return result_md5;
		// Log.v("he--------------------------------ji", "toMd5(): " + e);
		// throw new RuntimeException(e);
	}

	/**
	 * MD5 加密
	 * 
	 * @param
	 * @return
	 */
	public static String MD5(String str) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

		char[] charArray = str.toCharArray();
		byte[] byteArray = new byte[charArray.length];

		for (int i = 0; i < charArray.length; i++) {
			byteArray[i] = (byte) charArray[i];
		}
		byte[] md5Bytes = md5.digest(byteArray);

		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}

	/**
	 * 获取时间戳
	 * 
	 * @return
	 */
	// public static String getTimeStamp() {
	// NetConfig.TIME_STAMP = String.valueOf(System.currentTimeMillis());
	// return NetConfig.TIME_STAMP;
	// }

	/**
	 * 字符串匹配
	 * 
	 * @param expression
	 *            正则表达式字符串
	 * @param text
	 *            要进行匹配的字符串
	 */
	public static boolean matchingText(String expression, String text) {
		Pattern p = Pattern.compile(expression); // 正则表达式
		Matcher m = p.matcher(text); // 操作的字符串
		boolean b = m.matches();
		return b;
	}

	/**
	 * 去掉特殊字符
	 * 
	 * @param str
	 * @return
	 */
	public static String clearSpecificSymbol(String str) {
		String temp = str;
		if (temp.contains("&"))
			temp = temp.replaceAll("&", "");
		if (temp.contains("'"))
			temp = temp.replaceAll("'", "");
		return temp;
	}

	/**
	 * 判断是否符合手机号码
	 * 
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobile(String mobiles) {
		Pattern p = Pattern.compile("^(2|1)\\d{10}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	/**
	 * 判断是否符合Email
	 * 
	 * @param email
	 * @return
	 */
	public static boolean isEmail(String email) {

		int index_flag_1 = email.indexOf("@");
		if (index_flag_1 != -1 && index_flag_1 > 0
				&& index_flag_1 <= email.length() - 4) {// a@b.c
			return true;// email合法 @不在最前面，也不再最后面
		}
		return false;

	}

	/**
	 * 转换成标准的URL 其实我怀疑这个方法是否完备 Yoyo 2011-08-15
	 * 
	 * @param src
	 * @return
	 */
	public static String escapeSpecialCharForUrlSegments(String src) {
		return src.replace(" ", "%20").replace("[", "%5B").replace("]", "%5D")
				.replace("|", "%7C");
	}

	public static boolean haveInternet(Context context) {
		NetworkInfo info = ((ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE))
				.getActiveNetworkInfo();
		if (info == null || !info.isConnected()) {
			return false;
		}
		if (info.isRoaming()) {
			return true;
		}
		return true;
	}

	/***/
	/** * 图片去色,返回灰度图片 * @param bmpOriginal 传入的图片 * @return 去色后的图片 */
	// public static Bitmap toGrayscale(Bitmap bmpOriginal) {
	// int width, height;
	// height = bmpOriginal.getHeight();
	// width = bmpOriginal.getWidth();
	// Bitmap bmpGrayscale = Bitmap.createBitmap(width, height,
	// Bitmap.Config.RGB_565);
	// Canvas c = new Canvas(bmpGrayscale);
	// Paint paint = new Paint();
	// ColorMatrix cm = new ColorMatrix();
	// cm.setSaturation(0);
	// ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
	// paint.setColorFilter(f);
	// c.drawBitmap(bmpOriginal, 0, 0, paint);
	// return bmpGrayscale;
	// }

	/**
	 * 判断一个app是否已经安装
	 * 
	 * @param context
	 * @param packageName
	 * @return
	 */
	// public static boolean isAppInstalled(Context context, String packageName)
	// {
	// PackageInfo packageInfo;
	//
	// try {
	// packageInfo = context.getPackageManager().getPackageInfo( packageName,
	// 0);
	//
	// } catch (NameNotFoundException e) {
	// packageInfo = null;
	// e.printStackTrace();
	// }
	//
	// return packageInfo != null;
	// }

	/**
	 * 获取MAC地址
	 * 
	 * @param context
	 * @return
	 */
	public static String getMacAddress(Context context) {
		// return "14-FE-B5-A8-A0-8C";

		String mac = "E0:B9:A5:70:F1:3F";
		WifiManager wifi = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		if (null != wifi) {
			WifiInfo info = wifi.getConnectionInfo();
			if (null != info) {
				mac = info.getMacAddress();
				if (mac == null) {
					mac = "f0:f0:f0:f0:f0:f0";
				}
			}
		}

		return mac.toUpperCase();
	}

	/**
	 * 获取deviceID
	 * 
	 * @param context
	 * @return
	 */
	public static String getDeviceId(Context context) {
		String devId = "";

		TelephonyManager telephonyManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		if (telephonyManager != null)
			devId = telephonyManager.getDeviceId();
		if (devId == null)
			devId = "";
		Tool.Log("DEVICEID", devId);
		return devId;
	}

	/**
	 * 获取manifest里的渠道号
	 * 
	 * @param context
	 * @param key
	 * @return
	 */
	// public static String getMetaData(Context context, String key) {
	// try {
	// ApplicationInfo ai = context.getPackageManager()
	// .getApplicationInfo(context.getPackageName(),
	// PackageManager.GET_META_DATA);
	// Object value = ai.metaData.get(key);
	// if (value != null) {
	// return value.toString();
	// }
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// return null;
	// }

	/**
	 * ！！！！！注意，打包的时候记得吧canLog置为false！！！！！！！！！！！！！！！！！！！！！！！！后台输出关闭
	 */
	private static boolean canLog = true;

	public static void Log(String tag, String msg) {
		if (canLog) {
			Log.d(tag, msg);
		}
	}

	public static InputStream getFile(Context act, String dir, String name,
			String prefix) {
		try {
			String Path = dir + "/" + name + "." + prefix;
			return act.getAssets().open(Path);
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return null;
		}

	}
    public static InputStream getFile(Context act, String dir, String name) {
        try {
            String Path = dir + "/" + name;
            return act.getAssets().open(Path);
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
            return null;
        }
    }
    public static InputStream getFile(Context act, String path) {
        try {
            return act.getAssets().open(path);
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
            return null;
        }
    }
    public static String[] getFileList(Context act, String dir) {
        try {

            return act.getAssets().list(dir);
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
            return null;
        }

    }

}
